package com.thrd.taiexhibition.activity;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.flyco.tablayout.SlidingScaleTabLayout;
import com.thrd.basicframework.bean.BaseFragment;
import com.thrd.basicframework.bean.BaseRecyclerAdapter;
import com.thrd.basicframework.bean.CommonPopupWindow;
import com.thrd.basicframework.ui.LetterView;
import com.thrd.basicframework.ui.XViewPager;
import com.thrd.basicframework.ui.recyclerview.MaxHeightRecyclerView;
import com.thrd.basicframework.ui.recyclerview.RecyclerSpace;
import com.thrd.basicframework.ui.recyclerview.ScrollExpandableListView;
import com.thrd.basicframework.utils.DensityUtil;
import com.thrd.basicframework.utils.LogUtil;
import com.thrd.taiexhibition.BaseApplication;
import com.thrd.taiexhibition.adapter.HomeAdapter;
import com.thrd.taiexhibition.R;
import com.thrd.taiexhibition.adapter.HomeCityAdapter;
import com.thrd.taiexhibition.adapter.HomeHotCityAdapter;
import com.thrd.taiexhibition.adapter.PupopHomeAdapter;
import com.thrd.taiexhibition.bean.BaseActivity;
import com.thrd.taiexhibition.bean.BeanAD;
import com.thrd.taiexhibition.bean.BeanAdvert;
import com.thrd.taiexhibition.bean.BeanCity;
import com.thrd.taiexhibition.bean.BeanCityList;
import com.thrd.taiexhibition.bean.BeanHomeSort;
import com.thrd.taiexhibition.bean.CityEvent;
import com.thrd.taiexhibition.fragement.CityFragment;
import com.thrd.taiexhibition.fragement.ResearchFragment;
import com.thrd.taiexhibition.fragement.ThemeExhibitionFragment;
import com.thrd.taiexhibition.presener.HomePresener;
import com.thrd.taiexhibition.ui.AdImageSwitcher;
import com.thrd.taiexhibition.utils.ARouterUtils;
import com.thrd.taiexhibition.utils.DialogUtils;
import com.thrd.taiexhibition.utils.JumpUtils;
import com.thrd.taiexhibition.view.HomeView;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: ${唐杰}
 * @date: 2021/3/3
 */
@Route(path = "/app/home",group = "app")
public class HomeActivity extends BaseActivity implements HomeView, View.OnClickListener {

    private SlidingScaleTabLayout mSlidingTabLayout;
    private String[] mTitlesArrays ={" • 观城市   "," • 泰会展   "," • 有聊调研   "};
    private XViewPager mPager;
    private LinearLayout mTypeLayout;
    private CommonPopupWindow.Builder mBuilder;
    private LinearLayout mCode;
    private CityFragment fragment1;
    private ThemeExhibitionFragment fragment2;
    private HomePresener mHomePresener;
    private FrameLayout mLayoutCity;
    private ResearchFragment fragment4;
    private AdImageSwitcher mImageSwitcher;
    private TextView mCityName;
    private FrameLayout mCooperation;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        // AdvertisingWindow.getAdvertisingWindow(this,R.layout.popup_ad_bottom).showWindow();
        mHomePresener = new HomePresener(this);
//        mHomePresener.getCityListData();
//        mHomePresener.getClassBrowse();
        mHomePresener.getAdData();

        mSlidingTabLayout = findViewById(R.id.mSlidingTabLayout);
        mPager = findViewById(R.id.vp_pager);
        mCode = findViewById(R.id.fl_qr_code);
        mTypeLayout = findViewById(R.id.ll_logo_layout);
        mLayoutCity = findViewById(R.id.fl_layout_city);
        mImageSwitcher = findViewById(R.id.imageSwitcher);
        mCityName = findViewById(R.id.tv_city);
        mCooperation = findViewById(R.id.fl_cooperation_layout);

        mLayoutCity.setOnClickListener(this);
        mImageSwitcher.setOnItemClick(new AdImageSwitcher.OnItemClick() {
            @Override
            public void onItemClick(BeanAdvert mBeanAdvert) {
                if(mBeanAdvert!=null){
                    JumpUtils.JumpUtils(mBeanAdvert.getAdvertType(),mBeanAdvert.getRelevanceId());
                }
            }
        });
        fragment1 = new CityFragment();
        fragment2 = new ThemeExhibitionFragment();
        fragment4 = new ResearchFragment();
        List<BaseFragment> fragmentList=new ArrayList<>();
        fragmentList.add(fragment1);
        fragmentList.add(fragment2);
        fragmentList.add(fragment4);
        HomeAdapter adapter=new HomeAdapter(getSupportFragmentManager(),0,fragmentList);
        mPager.setAdapter(adapter);
        mSlidingTabLayout.setViewPager(mPager, mTitlesArrays);//tab和ViewPager进行关联
        mPager.setOffscreenPageLimit(3);
        mPager.setSlide(true);

        mTypeLayout.setOnClickListener(onClickListener);
        mCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtils.showQRDialog(HomeActivity.this,"");
            }
        });

        mCooperation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouterUtils.setCooperation();
            }
        });


    }
    private PupopHomeAdapter adapter;
    private View.OnClickListener onClickListener=new View.OnClickListener() {

        private CommonPopupWindow mCommonPopupWindow;

        @SuppressLint("ResourceType")
        @Override
        public void onClick(View v) {
            mTypeLayout.setBackgroundColor(Color.parseColor("#3F3F3F"));
            BaseApplication mBaseApplication= (BaseApplication) getApplication();
            if(mBaseApplication!=null&&mBaseApplication.getBeanSystemInfo()!=null&&mBaseApplication.getBeanSystemInfo().getClassBrowse()!=null){
                List<BeanHomeSort> mBeanHomeSortList=mBaseApplication.getBeanSystemInfo().getClassBrowse();

                if(mBuilder==null){
                    mBuilder = new  CommonPopupWindow.Builder(HomeActivity.this);
                    mBuilder.setView(R.layout.popup_home_view);
                    mBuilder.setAnimationStyle(R.style.MaterialDialogSheet);
                    mBuilder.setOutsideTouchable(true);
                    mBuilder.setWidthAndHeight(getResources().getDimensionPixelSize(R.dimen.qb_px_200),getResources().getDimensionPixelSize(R.dimen.qb_px_120));
                    mBuilder.setBackGroundLevel(0.7f);
                }

                if(mCommonPopupWindow==null&&mBuilder!=null){
                    mCommonPopupWindow = mBuilder.create();
                    View view= mCommonPopupWindow.getContentView();
                    RecyclerView mRecyclerView=view.findViewById(R.id.rv_recyclerview);
                    mRecyclerView.setLayoutManager(new GridLayoutManager(HomeActivity.this,3));
                    RecyclerSpace mRecyclerSpace= new RecyclerSpace(1,Color.parseColor("#3F3F3F"));
                    mRecyclerView.addItemDecoration(mRecyclerSpace);
                    adapter = new PupopHomeAdapter(HomeActivity.this,mBeanHomeSortList);
                    mRecyclerView.setAdapter(adapter);
                    adapter.setItemClick(new BaseRecyclerAdapter.ItemClick<BeanHomeSort>() {
                        @Override
                        public void onItemClick(int p, BeanHomeSort e) {
                            //ToastUtil.show(HomeActivity.this,"SkipType="+e.getSkipType());
                            JumpUtils.JumpUtils(e.getSkipType(),e.getOneRelevanceId());
                            mCommonPopupWindow.dismiss();
                        }
                    });
                }

//            if(adapter!=null){
//                adapter.refresh(beanStoryList);
//            }

                if(mCommonPopupWindow!=null){
                    mCommonPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            mTypeLayout.setBackgroundColor(Color.parseColor("#00000000"));
                        }
                    });
                    mCommonPopupWindow.showAsDropDown(v, DensityUtil.dip2px(HomeActivity.this,5),DensityUtil.dip2px(HomeActivity.this,3));
                }
            }





        }
    } ;





    @Override
    protected void onPause() {
        super.onPause();
        //   AdvertisingWindow.getAdvertisingWindow(this,R.layout.popup_ad_bottom).removeView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //   AdvertisingWindow.getAdvertisingWindow(this,R.layout.popup_ad_bottom).showWindow();
    }




    @Override
    public void onError(String error, int type) {

    }

    private BeanCityList mBeanCityList;

    @Override
    public void onSuccess(BeanCityList mBeanCityList) {
        this.mBeanCityList=mBeanCityList;
        if(mBeanCityList!=null){
            if(mHomeCityAdapter!=null){
                mHomeCityAdapter.setData(mBeanCityList.getListBeanCityLetters());
            }

            if(mHomeHotCityAdapter!=null){
                mHomeHotCityAdapter.setData(mBeanCityList.getCityList());
            }

        }

    }

    private List<BeanHomeSort> beanStoryList;
    @Override
    public void onSuccess(List<BeanHomeSort> beanStoryList) {
        this.beanStoryList=beanStoryList;
        if(adapter!=null){
            adapter.refresh(beanStoryList);
        }
    }
    private BeanAD mBeanAD;
    @Override
    public void onSuccess(BeanAD mBeanAD) {
        this.mBeanAD=mBeanAD;
        mImageSwitcher.setBeanAD(mBeanAD);
    }


    private CommonPopupWindow.Builder mBuilderCity;
    private CommonPopupWindow mCommonPopupWindowCity;

    private HomeHotCityAdapter mHomeHotCityAdapter;
    private HomeCityAdapter mHomeCityAdapter;
    private LetterView mLetterView;
    private MaxHeightRecyclerView mMaxHeightRecyclerView;
    private ScrollExpandableListView  mExpandableListView;
    private RecyclerView mRecyclerViewLetter;
    //城市选择
    private void popupCity(View view){
        BaseApplication mBaseApplication= (BaseApplication) getApplication();

        if(mBuilderCity==null&&mBaseApplication!=null){
            mBuilderCity = new  CommonPopupWindow.Builder(HomeActivity.this);
            mBuilderCity.setView(R.layout.popup_home_city);
            mBuilderCity.setOutsideTouchable(true);
            mBuilderCity.setAnimationStyle(R.style.popwindow_anim);
            mBuilderCity.setWidthAndHeight(getResources().getDimensionPixelSize(R.dimen.qb_px_171),getResources().getDimensionPixelSize(R.dimen.qb_px_302));
            if(mCommonPopupWindowCity==null){
                mCommonPopupWindowCity = mBuilderCity.create();
                View view1=mCommonPopupWindowCity.getContentView();
                mMaxHeightRecyclerView = view1.findViewById(R.id.mhrv_recyclerview);
                mExpandableListView = view1.findViewById(R.id.expandablelistview);
                mLetterView = view1.findViewById(R.id.ltv_textview);
                if(mHomeHotCityAdapter==null){
                    GridLayoutManager layoutManager = new GridLayoutManager(HomeActivity.this, 3, LinearLayoutManager.VERTICAL,false);
                    mMaxHeightRecyclerView.setLayoutManager(layoutManager);
                    mHomeHotCityAdapter=new HomeHotCityAdapter(HomeActivity.this,mBaseApplication.getHotCityList());
                    mMaxHeightRecyclerView.setAdapter(mHomeHotCityAdapter);
                    mHomeHotCityAdapter.setItemClick(new BaseRecyclerAdapter.ItemClick<BeanCity>() {
                        @Override
                        public void onItemClick(int p, BeanCity mBeanCity) {
                            setCitySetting(mBeanCity.getCityName(),mBeanCity.getCityId());
                            mCommonPopupWindowCity.dismiss();
                        }
                    });
                }

                if(mHomeCityAdapter==null&&mBaseApplication.getBeanCityList()!=null){
                    mHomeCityAdapter=new HomeCityAdapter(HomeActivity.this,mBaseApplication.getBeanCityList().getListBeanCityLetters());
                    mExpandableListView.setAdapter(mHomeCityAdapter);
                    for (int i = 0; i < mHomeCityAdapter.getGroupCount(); i++) {
                        mExpandableListView.expandGroup(i);
                    }

                    mExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
                        @Override
                        public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                            return true;
                        }
                    });

                    mHomeCityAdapter.setOnItemClick(new HomeCityAdapter.OnItemClick() {
                        @Override
                        public void onItemClick(BeanCity mBeanCity) {
                            setCitySetting(mBeanCity.getCityName(),mBeanCity.getCityId());
                            mCommonPopupWindowCity.dismiss();
                        }
                    });


                }
                mExpandableListView.setOnClickScrollStateChanged(new ScrollExpandableListView.OnClickScrollStateChanged() {
                    @Override
                    public void onClickScrollPosition(int position) {
                        LogUtil.e("ExpandableListView","position"+position);
                        mLetterView.setTouchIndex(position);
                    }
                });


                if(mBeanCityList!=null&&mBaseApplication.getBeanCityList()!=null){
                    mLetterView.setData(mBaseApplication.getBeanCityList().getLettersList());
                }
                mLetterView.setOnLetterChangeListener(new LetterView.OnLetterChangeListener() {
                    @Override
                    public void onLetterListener(String touchIndex, int position) {
                        mExpandableListView.scroll(position,0);
                    }

                    @Override
                    public void onLetterDismissListener() {

                    }
                });
            }

        }

        if(mCommonPopupWindowCity!=null)
            mCommonPopupWindowCity.showAsDropDown(view,0,getResources().getDimensionPixelSize(R.dimen.qb_px_2), Gravity.BOTTOM);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.fl_layout_city:
                popupCity(v);
                break;
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        if(mImageSwitcher!=null){
            mImageSwitcher.onStrat();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(mImageSwitcher!=null){
            mImageSwitcher.onStop();
        }
    }



    public void startAdAnimention(){

                //v.setTranslationX();//平移。当旋转时，下面的方法要对应的修
         if(mImageSwitcher!=null){
             mImageSwitcher.onStop();
             ObjectAnimator animator12=ObjectAnimator.ofFloat(mImageSwitcher,"TranslationY",0,mImageSwitcher.getHeight());
             AnimatorSet animatorSet=new AnimatorSet();
             animatorSet.playTogether(animator12);
             animatorSet.setDuration(500);
             animatorSet.addListener(new Animator.AnimatorListener() {
                 @Override
                 public void onAnimationStart(Animator animation) {

                 }

                 @Override
                 public void onAnimationEnd(Animator animation) {
                    // mImageSwitcher.setEnabled(true);
                 }

                 @Override
                 public void onAnimationCancel(Animator animation) {

                 }

                 @Override
                 public void onAnimationRepeat(Animator animation) {

                 }
             });
             animatorSet.start();
         }


    }

    public void recoveryAdAnimention(){

        //v.setTranslationX();//平移。当旋转时，下面的方法要对应的修
        if(mImageSwitcher!=null){
            mImageSwitcher.onStrat();
            ObjectAnimator animator12=ObjectAnimator.ofFloat(mImageSwitcher,"TranslationY",0,0);
            AnimatorSet animatorSet=new AnimatorSet();
            animatorSet.playTogether(animator12);
            animatorSet.setDuration(500);
            animatorSet.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                  //  mImageSwitcher.setEnabled(false);
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            animatorSet.start();
        }


    }





    /**
     * 城市切换
     * @param name
     * @param cityId
     */
    public void setCitySetting(String name,long cityId){
        BaseApplication baseApplication = (BaseApplication) getApplication();

        if(baseApplication!=null&&baseApplication.getCityId()!=cityId){
            baseApplication.setCityId(cityId);
            //设置城市名称
            if(mCityName!=null){
                mCityName.setText(TextUtils.isEmpty(name)?"":name);
            }
            //发送切换城市的事件
            EventBus.getDefault().post(new CityEvent(cityId));
        }

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return false;
    }
}
